package com.longrise.android.widget.LSlideMenu;

import com.longrise.android.widget.LSlideMenu.CustomLayout.OnScrollListener;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class LSlideMenuView extends RelativeLayout implements OnGestureListener, OnTouchListener{

	private RelativeLayout mainLayout;
	private LinearLayout leftLayout;
	private LinearLayout rightLayout;
	private CustomLayout customSlidMenuView;
	
	private View leftBtn;
	private View rightBtn;
	private GestureDetector mGestureDetector;
	
	private static final int SPEED = 30;
	private boolean bIsScrolling = false;
	private int iLimited = 0;
	private int mScroll = 0;
	private View mClickedView = null;
	private Context context = null;
	
	private boolean leftShow = false;
	private boolean rightShow = false;
	
	private int width = -1;
	
	public LSlideMenuView(Context context)
	{
		super(context);
		this.context = context;
		initView();
	}
	public LSlideMenuView(Context context, AttributeSet attrs) 
	{
		super(context, attrs);
		this.context = context;
		initView();
	}
	
	@SuppressWarnings("deprecation")
	private void initView()
	{
		mainLayout = new RelativeLayout(context);
		this.addView(mainLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		
		customSlidMenuView = new CustomLayout(context, null);
		customSlidMenuView.setOnScrollListener(new OnScrollListener(){
			@Override
			public void doOnScroll(MotionEvent e1, MotionEvent e2,
					float distanceX, float distanceY) {
				onScroll(distanceX);
			}
			
			@Override
			public void doOnRelease(){
				onRelease();
			}
		});
		mainLayout.addView(customSlidMenuView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		
		//左侧布局
		leftLayout = new LinearLayout(context);
		this.addView(leftLayout, 0, LayoutParams.MATCH_PARENT);
		
		//右侧布局
		rightLayout = new LinearLayout(context);
		this.addView(rightLayout, 0, LayoutParams.MATCH_PARENT);
		
		mainLayout.setOnTouchListener(this);
		leftLayout.setOnTouchListener(this);
		rightLayout.setOnTouchListener(this);
		
		mGestureDetector = new GestureDetector(this);
		mGestureDetector.setIsLongpressEnabled(false);
		
		DisplayMetrics dm = getResources().getDisplayMetrics();
		resizeLayout(dm.widthPixels);
	}
	
	public void addViewBody(View view)
	{
		if(null == view)
		{
			return;
		}
		if(null != customSlidMenuView)
		{
			customSlidMenuView.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		}
	}
	
	/**
	 * 设置宽度,默认是屏幕的宽度
	 */
	public void setViewWidth(int width)
	{
		if(width > 0)
		{
			this.width = width;
			resizeLayout(this.width);
		}
	}
	
	/**
	 * 设置做按钮
	 */
	public void setLeftBtn(View leftBtn)
	{
		if(null != leftBtn)
		{
			this.leftBtn = leftBtn;
			this.leftBtn.setOnTouchListener(this);
		}
	}
	
	public void setRightBtn(View rightBtn)
	{
		if(null != rightBtn)
		{
			this.rightBtn = rightBtn;
			this.rightBtn.setOnTouchListener(this);
		}
	}
	
	/**
	 * 添加左边的布局，默认不显示
	 */
	public void addLeftView(View leftView,int leftViewWidth)
	{
		if(leftView == null)
		{
			return;
		}
		
		if(null != leftLayout)
		{
			LayoutParams lp = (LayoutParams) leftLayout.getLayoutParams();
			if(null != lp)
			{
				lp.width = leftViewWidth;
				leftLayout.setLayoutParams(lp);
			}
			lp = null;
			leftLayout.removeAllViews();
			leftLayout.addView(leftView);
			resizeLayout(this.width);
		}
	}
	/**
	 * 添加右边的布局，默认不显示
	 */
	public void addRightView(View rightView,int rightViewWidth)
	{
		if(rightView == null)
		{
			return;
		}
		
		if(null != rightLayout)
		{
			LayoutParams lp = (LayoutParams) rightLayout.getLayoutParams();
			if(null != lp)
			{
				lp.width = rightViewWidth;
				rightLayout.setLayoutParams(lp);
			}
			lp = null;
			rightLayout.removeAllViews();
			rightLayout.addView(rightView);
			resizeLayout(this.width);
		}
	}
	/**
	 * 添加中间的布局
	 */
	public void addBodyView(View bodyView)
	{
		if(bodyView == null)
		{
			return;
		}
		
		if(null != customSlidMenuView)
		{
			customSlidMenuView.addView(bodyView);
		}
		resizeLayout(this.width);
	}
	
	/*
	 * 使用leftMargin及rightMargin防止layout被挤压变形
	 * Math.abs(leftMargin - rightMargin) = layout.width
	 */
	private void resizeLayout(int width)
	{
		DisplayMetrics dm = getResources().getDisplayMetrics();
		dm.widthPixels = width;
		// 固定 main layout, 防止被左、右挤压变形
		RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
		lp.width = dm.widthPixels;
		mainLayout.setLayoutParams(lp);
		
		// 将左layout调整至main layout左边
		lp = (android.widget.RelativeLayout.LayoutParams) leftLayout.getLayoutParams();
		lp.leftMargin = -lp.width;
		leftLayout.setLayoutParams(lp);
		
		// 将左layout调整至main layout右边
		lp = (android.widget.RelativeLayout.LayoutParams) rightLayout.getLayoutParams();
		lp.leftMargin = dm.widthPixels;
		lp.rightMargin = -lp.width;
		rightLayout.setLayoutParams(lp);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
			
			if(lp.leftMargin != 0){
				if(lp.leftMargin > 0){
					new SlideMenu().execute(leftLayout.getLayoutParams().width, -SPEED);
				}else if(lp.leftMargin < 0){
					new SlideMenu().execute(rightLayout.getLayoutParams().width, SPEED);
				}
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void rollLayout(int margin)
	{
		RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
		lp.leftMargin += margin;
		lp.rightMargin -= margin;
		mainLayout.setLayoutParams(lp);
		lp = (android.widget.RelativeLayout.LayoutParams) leftLayout.getLayoutParams();
		lp.leftMargin += margin;
		leftLayout.setLayoutParams(lp);
		lp = (android.widget.RelativeLayout.LayoutParams) rightLayout.getLayoutParams();
		lp.leftMargin += margin;
		lp.rightMargin -= margin;
		rightLayout.setLayoutParams(lp);
	}

	private void onScroll(float distanceX)
	{
		bIsScrolling = true;
		mScroll += distanceX;  // 向左为正
		
		RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
		RelativeLayout.LayoutParams lpLeft = (android.widget.RelativeLayout.LayoutParams) leftLayout.getLayoutParams();
		RelativeLayout.LayoutParams lpRight = (android.widget.RelativeLayout.LayoutParams) rightLayout.getLayoutParams();
		
		int distance = 0;
		if(mScroll > 0)
		{ 
			// 向左移动
			if(lp.leftMargin <= 0)
			{ 
				// 打开右导航菜单
				if(iLimited > 0)
				{
					return;
				}
				distance = lpRight.width - Math.abs(lp.leftMargin);
			}
			else if(lp.leftMargin > 0)
			{ 
				// 关闭左导航菜单
				distance = lp.leftMargin;
			}
			if(mScroll >= distance)
			{
				mScroll = distance;
			}
		}
		else if(mScroll < 0)
		{  
			// 向右移动
			if(lp.leftMargin >= 0)
			{ 
				// 打开左导航菜单
				if(iLimited < 0)
				{
					return;
				}
				distance = lpLeft.width - Math.abs(lp.leftMargin);
			}
			else if(lp.leftMargin < 0)
			{ 
				// 关闭右导航菜单
				distance = Math.abs(lp.leftMargin);
			}
			if(mScroll <= -distance)
			{
				mScroll = -distance;
			}
		}

		if(mScroll != 0)
		{
			rollLayout(-mScroll);
		}
	}
	
	private void onRelease(){
		RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
		if(lp.leftMargin < 0)
		{ 
			// 左移
			/*
			 * 	左移大于右导航宽度一半，则自动展开,否则自动缩回去
			 */
			if(Math.abs(lp.leftMargin) > rightLayout.getLayoutParams().width/2)
			{
				new SlideMenu().execute(rightLayout.getLayoutParams().width - Math.abs(lp.leftMargin), -SPEED);
			}
			else
			{
				new SlideMenu().execute(Math.abs(lp.leftMargin), SPEED);
			}
		}
		else if(lp.leftMargin > 0)
		{
			/*
			 * 	右移大于左导航宽度一半，则自动展开,否则自动缩回去
			 */
			if(Math.abs(lp.leftMargin) > leftLayout.getLayoutParams().width/2)
			{
				new SlideMenu().execute(leftLayout.getLayoutParams().width - Math.abs(lp.leftMargin), SPEED);
			}
			else
			{
				new SlideMenu().execute(Math.abs(lp.leftMargin), -SPEED);
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) 
	{
		mClickedView = v;
		
		if(MotionEvent.ACTION_UP == event.getAction() && bIsScrolling){
			onRelease();
		}
		return mGestureDetector.onTouchEvent(event);
	}
	
	// GestureDetector Override Begin
	@Override
	public boolean onDown(MotionEvent e) 
	{
		
		bIsScrolling = false;
		mScroll = 0;
		iLimited = 0;
		RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
		if(lp.leftMargin > 0)
		{
			iLimited = 1;
		}
		else if(lp.leftMargin < 0)
		{
			iLimited = -1;
		}
		
		return true;
	}

	@Override
	public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) 
	{
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) 
	{
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) 
	{
		onScroll(distanceX);
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) 
	{
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e)
	{
		/*
		 * 	正常情况下，mainLayout的leftMargin为0,
		 * 	当左/右菜单为打开中，此时就不为0，需要判断
		 */
		if(mClickedView != null)
		{
			RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
			
			if(mClickedView == leftBtn)
			{
				
				if(lp.leftMargin == 0)
				{
					new SlideMenu().execute(leftLayout.getLayoutParams().width, SPEED);
				}
				else
				{
					new SlideMenu().execute(leftLayout.getLayoutParams().width, -SPEED);
				}
			}
			else if(mClickedView == rightBtn)
			{
				
				if(lp.leftMargin == 0)
				{
					new SlideMenu().execute(rightLayout.getLayoutParams().width, -SPEED);
				}
				else
				{
					new SlideMenu().execute(rightLayout.getLayoutParams().width, SPEED);
				}
			}
			else if(mClickedView == mainLayout)
			{
			}
		}
		return true;
	}
	/////////////////// GestureDetector Override End ///////////////////
	
	/**
	 * 
	 * @author cheng.yang
	 *
	 *	左、右菜单滑出
	 *
	 *	params[0]: 滑动距离
	 *	params[1]: 滑动速度,带方向
	 */
	public class SlideMenu extends AsyncTask<Integer, Integer, Void>{
		@Override
		protected Void doInBackground(Integer... params) 
		{
			if(params.length != 2)
			{
			}

			int times = params[0] / Math.abs(params[1]);
			if(params[0] % Math.abs(params[1]) != 0)
			{
				times ++;
			}
			
			for(int i = 0; i < times; i++)
			{
				this.publishProgress(params[0], params[1], i+1);
			}
			
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) 
		{
			if(values.length != 3)
			{
			}

			int distance = Math.abs(values[1]) * values[2];
			int delta = values[0] - distance;

			int leftMargin = 0;
			if(values[1] < 0)
			{ // 左移
				leftMargin = (delta > 0 ? values[1] : -(Math.abs(values[1]) - Math.abs(delta)));
			}
			else
			{
				leftMargin = (delta > 0 ? values[1] : (Math.abs(values[1]) - Math.abs(delta)));
			}
			
			rollLayout(leftMargin);
		}
	}
	
	/**
	 * 显示或者关闭左边布局
	 * 当左边显示时就关闭，关闭时就打开
	 */
	public void ShowOrCloseLeft()
	{
		mClickedView = leftBtn;
		if(mClickedView != null)
		{
			RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
			
			if(mClickedView == leftBtn)
			{
				
				if(lp.leftMargin == 0)
				{
					new SlideMenu().execute(leftLayout.getLayoutParams().width, SPEED);
				}
				else
				{
					new SlideMenu().execute(leftLayout.getLayoutParams().width, -SPEED);
				}
			}
		}
	}
	
	/**
	 * 显示或者关闭右边布局
	 * 当左边显示时就关闭，关闭时就打开
	 */
	public void ShowOrCloseRight()
	{
		mClickedView = rightBtn;
		if(mClickedView != null)
		{
			RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
		
			if(mClickedView == rightBtn)
			{
				
				if(lp.leftMargin == 0)
				{
					new SlideMenu().execute(rightLayout.getLayoutParams().width, -SPEED);
				}
				else
				{
					new SlideMenu().execute(rightLayout.getLayoutParams().width, SPEED);
				}
			}
		}
	}
	
	public void onDestory()
	{
		mainLayout = null;
		leftLayout = null;
		rightLayout = null;
		customSlidMenuView = null;
		leftBtn = null;
		rightBtn = null;
		mGestureDetector = null;
		mClickedView = null;
		context = null;
	}
}
